<?php

namespace app\api\controller\v1\team;

use app\Request;
use app\dao\crud\TeamApplicationDao;
use app\model\crud\TeamApplicationModel;
use app\model\crud\Team;
use crmeb\exceptions\ApiException;

class TeamApplication
{
    /**
     * 申请加入队伍
     * @param Request $request
     * @return \think\Response
     */
    public function apply(Request $request)
    {
        try {
            $uid = $request->uid();
            $teamId = $request->param('team_id');
            
            if (!$teamId) {
                return app('json')->fail('队伍ID不能为空');
            }

            // 直接使用模型查询队伍信息
            $teamModel = app()->make(\app\model\crud\Team::class);
            $team = $teamModel->where('id', $teamId)->find();
            
            if (!$team) {
                return app('json')->fail('队伍不存在');
            }

            // 检查是否已经是队伍成员
            if (!empty($team['user_ids']) && strpos($team['user_ids'], (string)$uid) !== false) {
                return app('json')->fail('您已经是该队伍的成员');
            }

            // 直接使用模型检查是否已经申请过
            $applicationModel = app()->make(TeamApplicationModel::class);
            $existingApplication = $applicationModel->where('uid', $uid)
                ->where('team_id', $teamId)
                ->find();
            
            if ($existingApplication) {
                return app('json')->fail('您已经申请过该队伍，请等待审核');
            }

            // 创建申请记录
            $data = [
                'team_id' => $teamId,
                'uid' => $uid,
                'type' => TeamApplicationModel::TYPE_APPLY,
                'status' => TeamApplicationModel::STATUS_PENDING
            ];

            $result = $applicationModel->create($data);
            
            if ($result) {
                return app('json')->success('申请提交成功，请等待审核');
            } else {
                return app('json')->fail('申请提交失败');
            }
        } catch (\Exception $e) {
            // 记录详细错误信息用于调试
            \think\facade\Log::error('Apply接口错误: ' . $e->getMessage() . ' 文件: ' . $e->getFile() . ' 行号: ' . $e->getLine());
            return app('json')->fail('申请提交失败：' . $e->getMessage());
        }
    }

    /**
     * 邀请用户加入队伍
     * @param Request $request
     * @return \think\Response
     */
    public function invite(Request $request)
    {
        try {
            $adminUid = $request->uid();
            $uid = $request->param('uid');
            $teamId = $request->param('team_id');

            if (!$uid || !$teamId) {
                return app('json')->fail('用户ID和队伍ID不能为空');
            }

            $teamDao = app()->make(\app\dao\crud\TeamDao::class);

            $team = $teamDao->get($teamId);
            if (!$team) {
                return app('json')->fail('队伍不存在');
            }

            // 检查是否为队长
            if ($team['admin_uid'] != $adminUid) {
                return app('json')->fail('您不是该队伍的队长，无权邀请用户');
            }

            // 检查用户是否已经是队伍成员
//        if (strpos($team['user_ids'].'', $uid.'') !== false) {
//            return app('json')->fail('该用户已经是队伍成员');
//        }

            $applicationDao = app()->make(TeamApplicationDao::class);

            // 检查是否已经邀请过
//            if ($applicationDao->hasApplied($uid, $teamId)) {
//                return app('json')->fail('您已经邀请过该用户');
//            }

            // 创建邀请记录
            $data = [
                'team_id' => $teamId,
                'uid' => $uid,
                'type' => TeamApplicationModel::TYPE_INVITE,
                'status' => TeamApplicationModel::STATUS_APPROVED,
            ];

            $result = $applicationDao->save($data);

            if ($result) {
                $team->user_ids = $uid.','.$team->user_ids;
                $team->save();
                return app('json')->success('邀请发送成功');
            } else {
                return app('json')->fail('邀请发送失败');
            }
        }catch (ApiException $exception){
            return app('json')->fail($exception->getMessage());
        }
    }

    /**
     * 获取我的申请记录
     * @param Request $request
     * @return \think\Response
     */
    public function myApplications(Request $request)
    {
        try {
            $uid = $request->uid();
            $status = $request->param('status', ''); // 可选的状态筛选
            
            $where = [];
            if ($status !== '') {
                $where['status'] = $status;
            }

            // 直接使用模型查询，避免复杂的关联查询
            $applicationModel = app()->make(TeamApplicationModel::class);
            $applications = $applicationModel->where('uid', $uid)
                ->when(!empty($where['status']), function($query) use ($where) {
                    $query->where('status', $where['status']);
                })
                ->order('create_time desc')
                ->select();
            
            // 批量获取队伍信息
            $teamIds = array_unique(array_column($applications->toArray(), 'team_id'));
            $teamModel = app()->make(\app\model\crud\Team::class);
            $teams = $teamModel->whereIn('id', $teamIds)->column('id,name,avatar', 'id');
            
            // 批量获取报名信息
            $baomingModel = app()->make(\app\model\crud\Baoming::class);
            $baomings = $baomingModel->where('uid', $uid)->find();
            
            // 格式化数据
            $list = [];
            foreach ($applications as $application) {
                $team = $teams[$application['team_id']] ?? null;
                
                $list[] = [
                    'id' => $application['id'],
                    'team_id' => $application['team_id'],
                    'team_name' => $team['name'] ?? '',
                    'team_avatar' => $team['avatar'] ?? '',
                    'type' => $application['type'],
                    'type_text' => TeamApplicationModel::getTypeText($application['type']),
                    'status' => $application['status'],
                    'status_text' => TeamApplicationModel::getStatusText($application['status']),
                    'baoming_info' => $baomings ? [
                        'name' => $baomings['name'] ?? '',
                        'school_card' => $baomings['school_card'] ?? '',
                        'mobile' => $baomings['mobile'] ?? '',
                        'game_id' => $baomings['game_id'] ?? '',
                        'sancang' => $baomings['sancang'] ?? ''
                    ] : null,
                    'create_time' => $application['create_time'],
                    'update_time' => $application['update_time']
                ];
            }

            return app('json')->success(compact('list'));
        } catch (\Exception $e) {
            return app('json')->fail('获取申请记录失败：' . $e->getMessage());
        }
    }

    /**
     * 获取队伍的申请记录（队长权限）
     * @param Request $request
     * @return \think\Response
     */
    public function teamApplications(Request $request)
    {
        try {
            $uid = $request->uid();
            $teamId = $request->param('team_id');
            $status = $request->param('status', ''); // 可选的状态筛选
            
            if (!$teamId) {
                return app('json')->fail('队伍ID不能为空');
            }

            // 检查是否为队长
            $teamDao = app()->make(\app\dao\crud\TeamDao::class);
            $team = $teamDao->get($teamId);

            if (!$team || $team['admin_uid'] != $uid) {
                return app('json')->fail('您不是该队伍的队长，无权查看申请记录');
            }

            $where = [];
            if ($status !== '') {
                $where['status'] = $status;
            }

            $applicationDao = app()->make(TeamApplicationModel::class);
            $applications = $applicationDao->with('baoming')
                ->where('status',0)
                ->where('team_id',$teamId)->select();

            // 格式化数据
            $list = [];
            foreach ($applications as $application) {
                $list[] = [
                    'id' => $application['id'],
                    'uid' => $application['uid'],
                    'user_nickname' => $application['user']['nickname'] ?? '',
                    'user_avatar' => $application['user']['avatar'] ?? '',
                    'type' => $application['type'],
                    'type_text' => TeamApplicationModel::getTypeText($application['type']),
                    'status' => $application['status'],
                    'status_text' => TeamApplicationModel::getStatusText($application['status']),
                    'baoming_info' => $application['baoming'] ? [
                        'name' => $application['baoming']['name'] ?? '',
                        'school_card' => $application['baoming']['school_card'] ?? '',
                        'mobile' => $application['baoming']['mobile'] ?? '',
                        'game_id' => $application['baoming']['game_id'] ?? '',
                        'sancang' => $application['baoming']['sancang'] ?? ''
                    ] : null,
                    'create_time' => $application['create_time'],
                    'update_time' => $application['update_time']
                ];
            }

            return app('json')->success(compact('list'));
        } catch (\Exception $e) {
            return app('json')->fail('获取队伍申请记录失败：' . $e->getMessage());
        }
    }

    /**
     * 审核申请（队长权限）
     * @param Request $request
     * @return \think\Response
     */
    public function review(Request $request)
    {
        try {
            $uid = $request->uid();
            $applicationId = $request->param('id');
            $status = $request->param('status'); // 1=通过, 2=拒绝
            
            if (!$applicationId || !in_array($status, [TeamApplicationModel::STATUS_APPROVED, TeamApplicationModel::STATUS_REJECTED])) {
                return app('json')->fail('参数错误');
            }

            $applicationDao = app()->make(TeamApplicationModel::class);
            $application = $applicationDao->where('id',$applicationId)->find();
            
            if (!$application) {
                return app('json')->fail('申请记录不存在');
            }

            // 检查是否为队长
            $teamDao = app()->make(\app\dao\crud\TeamDao::class);
            $team = $teamDao->get($application['team_id']);
            
            if (!$team || $team['admin_uid'] != $uid) {
                return app('json')->fail('您不是该队伍的队长，无权审核申请');
            }

            // 检查申请状态
            if ($application['status'] != TeamApplicationModel::STATUS_PENDING) {
                return app('json')->fail('该申请已经处理过了');
            }

            // 更新申请状态
            $result =$applicationDao->where('id',$applicationId)->update(['status'=>$status]);

            if ($result) {
                // 如果通过申请，将用户加入队伍
                if ($status == TeamApplicationModel::STATUS_APPROVED) {
                    $teamModel = app()->make(Team::class);
                    $teamModel->where('id', $application['team_id'])
                        ->update(['user_ids' => $application['uid'] . ',' . $team['user_ids']]);
                }
                
                $statusText = $status == TeamApplicationModel::STATUS_APPROVED ? '通过' : '拒绝';
                return app('json')->success("申请已{$statusText}");
            } else {
                return app('json')->fail('审核失败');
            }
        } catch (\Exception $e) {
            return app('json')->fail('审核申请失败：' . $e->getMessage());
        }
    }

    /**
     * 批量审核申请（队长权限）
     * @param Request $request
     * @return \think\Response
     */
    public function batchReview(Request $request)
    {
        $uid = $request->uid();
        $applicationIds = $request->param('application_ids', []);
        $status = $request->param('status'); // 1=通过, 2=拒绝
        
        if (empty($applicationIds) || !in_array($status, [TeamApplicationModel::STATUS_APPROVED, TeamApplicationModel::STATUS_REJECTED])) {
            return app('json')->fail('参数错误');
        }

        $applicationDao = app()->make(TeamApplicationDao::class);
        
        // 检查所有申请是否都属于该队长管理的队伍
        $applications = $applicationDao->getModel()->whereIn('id', $applicationIds)
            ->where('status', TeamApplicationModel::STATUS_PENDING)
            ->select();
        
        $teamDao = app()->make(\app\dao\crud\TeamDao::class);
        foreach ($applications as $application) {
            $team = $teamDao->get($application['team_id']);
            if (!$team || $team['admin_uid'] != $uid) {
                return app('json')->fail('您无权审核该申请');
            }
        }

        // 批量更新状态
        $result = $applicationDao->batchUpdateStatus($applicationIds, $status);
        
        if ($result) {
            // 如果通过申请，将用户加入队伍
            if ($status == TeamApplicationModel::STATUS_APPROVED) {
                $teamModel = app()->make(Team::class);
                foreach ($applications as $application) {
                    $team = $teamDao->get($application['team_id']);
                    $teamModel->where('id', $application['team_id'])
                        ->update(['user_ids' => $application['uid'] . ',' . $team['user_ids']]);
                }
            }
            
            $statusText = $status == TeamApplicationModel::STATUS_APPROVED ? '通过' : '拒绝';
            return app('json')->success("批量审核完成，申请已{$statusText}");
        } else {
            return app('json')->fail('批量审核失败');
        }
    }

    /**
     * 取消申请
     * @param Request $request
     * @return \think\Response
     */
    public function cancel(Request $request)
    {
        $uid = $request->uid();
        $applicationId = $request->param('application_id');
        
        if (!$applicationId) {
            return app('json')->fail('申请ID不能为空');
        }

        $applicationDao = app()->make(TeamApplicationDao::class);
        $application = $applicationDao->get($applicationId);
        
        if (!$application || $application['uid'] != $uid) {
            return app('json')->fail('申请记录不存在或您无权操作');
        }

        if ($application['status'] != TeamApplicationModel::STATUS_PENDING) {
            return app('json')->fail('该申请已经处理过了，无法取消');
        }

        $result = $applicationDao->delete($applicationId);
        
        if ($result) {
            return app('json')->success('申请已取消');
        } else {
            return app('json')->fail('取消失败');
        }
    }

    /**
     * 获取待审核申请数量（队长权限）
     * @param Request $request
     * @return \think\Response
     */
    public function pendingCount(Request $request)
    {
        $uid = $request->uid();
        $teamId = $request->param('team_id');
        
        if (!$teamId) {
            return app('json')->fail('队伍ID不能为空');
        }

        // 检查是否为队长
        $teamDao = app()->make(\app\dao\crud\TeamDao::class);
        $team = $teamDao->get($teamId);
        
        if (!$team || $team['admin_uid'] != $uid) {
            return app('json')->fail('您不是该队伍的队长');
        }

        $applicationDao = app()->make(TeamApplicationDao::class);
        $count = $applicationDao->getPendingCount($teamId);
        
        return app('json')->success(compact('count'));
    }
}
